import {Toast} from "antd-mobile";
import {useEffect, useState} from "react";

interface PaginationProps {
    pageSize: number;
    pageNo: number;
    [key: string]: any;
}
interface UseScrollDataProps {
    fetch: (e?: any) => any;
    params?: any;
    deep?: any[];
    pageNum?: "pageNo";
}
interface UseScrollDataExport {
    data?: any[];
    over?: boolean;
    pageNo?: string;
    setQuery: (e?: any) => any;
    handleResetRefresh?: (e?: any) => any;
    bottomRefresh: (e?: any) => any;
}

const useScrollData = (
    {fetch, pageNum = "pageNo", params = {}}: UseScrollDataProps,
    deep: any[] = []
): UseScrollDataExport => {
    const [over, setOver] = useState(true); //true 代表还有数据 false 代表没有数据
    const [query, setQuery] = useState<any>({});
    const [data, setData] = useState<any[]>([]);
    const [total, setTotal] = useState(10);
    const [pagination, setPagination] = useState<PaginationProps>({
        pageSize: 10,
        pageNo: 1,
    });

    const bottomRefresh = () => {
        const {pageNo, pageSize} = pagination;
        if (total > pageNo * pageSize) {
            const page: PaginationProps = {pageNo: pageNo + 1, pageSize: 10};
            return handleInit(page);
        }
    };

    const handleInit = (page: any = "") => {
        const paging: any = page || pagination;
        const {pageNo, pageSize} = paging;
        if (!setOver) {
            Toast.show({content: "没有多余数据啦..."});
        }
        const toast = Toast.show({icon: "loading", content: "加载中..."});
        return fetch({[pageNum]: pageNo, pageSize, ...params}).then(res => {
            if (pageNo === 1) {
                setData(res.data || []);
            } else {
                setData([...data, ...res.data]);
            }
            setTotal(res.total);
            if (res.total <= pageNo * pageSize) {
                setOver(false);
            } else {
                setOver(true);
            }
            setPagination({pageNo: pageNo, pageSize: pageSize});
            toast.close();
            return res;
        });
    };

    const handleResetRefresh = () => {
        return handleInit({pageNo: 1, pageSize: 10});
    };

    useEffect(() => {
        handleInit();
    }, [query, ...deep]);

    return {data, over, setQuery, handleResetRefresh, bottomRefresh};
};

export default useScrollData;
